package biznussoft.fieldservice360.fragments;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.MenuItemCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import biznussoft.fieldservice360.HomeActivity;
import biznussoft.fieldservice360.R;
import biznussoft.fieldservice360.adapter.ServiceOrderAdapter;
import biznussoft.fieldservice360.listeners.InventoryListener;
import biznussoft.fieldservice360.model.ActivityModel;
import biznussoft.fieldservice360.model.Bean_Class;
import biznussoft.fieldservice360.model.ServiceOrderModel;

import com.google.gson.Gson;
import com.salesforce.androidsdk.app.SalesforceSDKManager;
import com.salesforce.androidsdk.rest.RestClient;
import com.salesforce.androidsdk.rest.RestClient.AsyncRequestCallback;
import com.salesforce.androidsdk.rest.RestRequest;
import com.salesforce.androidsdk.rest.RestResponse;
import com.salesforce.androidsdk.util.EventsObservable;
import com.salesforce.androidsdk.util.EventsObservable.EventType;

public class ServiceOrderFragment  extends BaseFragment implements OnItemClickListener{
	private RestClient client;
	private ListView lv;
	static ArrayList<ServiceOrderModel> serviceOrderList;
	static ArrayList<ActivityModel> serviceOrderSubList;
	static HashMap<String, ArrayList<ActivityModel>> activityDetailsList;
	InventoryListener listener;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		return inflater.inflate(R.layout.inventory, null);
	}         

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);

	}
	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		// TODO Auto-generated method stub
		super.onCreateOptionsMenu(menu, inflater);


		MenuItem actionItem = menu.add("Logout");                 
		MenuItemCompat.setShowAsAction(actionItem,MenuItemCompat.SHOW_AS_ACTION_ALWAYS | MenuItemCompat.SHOW_AS_ACTION_WITH_TEXT);
		actionItem.setIcon(R.drawable.logout); 

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		if(item.getTitle().equals("Logout")){
			SalesforceSDKManager.getInstance().logout(getActivity());}
		return super.onOptionsItemSelected(item);
	}
	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		super.onAttach(activity);
		listener = (InventoryListener) getActivity();
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		lv = (ListView) getView().findViewById(R.id.listview);
		client =  HomeActivity.mActivity.client;
		Bean_Class.api_Version = getString(R.string.api_version);
		Task task = new Task();
		task.execute();     
		
		lv.setOnItemClickListener(this);

	}
                      
	class Task extends AsyncTask<Void, Void, Void>{

		@Override
		protected Void doInBackground(Void... params) {
			retriveLeads();
			return null;
		}

	}

	public void retriveLeads()        
	{
		try{
			String serviceOrder = "SELECT Name,Id,FConnect__Contact_Name__c,FConnect__Account_Name__c,FConnect__Account__c,FConnect__Adress__c,FConnect__Billable__c,FConnect__Bill_To_Address__c,FConnect__Contact__c,FConnect__Site_Name__c,FConnect__No_Of_Activities__c,FConnect__Alternate_Phone__c,FConnect__Priority__c,FConnect__Status__c,FConnect__Start_Date__c,FConnect__Installed_Product2__c,FConnect__Warranty_used__c,FConnect__Agreement__c,FConnect__Entitlement_Plan_Name__c,FConnect__Product_ID__c,FConnect__Service__c,FConnect__Agreement_Line__c,FConnect__Service_Discription__c,FConnect__Product_ID2__c,Agreement_Name__c,Entitlement_Group_Name__c,Service_Name__c,(SELECT Id,Name,FConnect__Activity__c,FConnect__Status__c,FConnect__Planned_End_Date_Time__c,FConnect__Planned_Start_DateTime__c,FConnect__Duration__c,FConnect__Billable__c,Activity_Name__c FROM FConnect__Activities__r) FROM FConnect__Service_Order__c";
			Log.i("TPT","SOQL is     :"+serviceOrder);

			RestRequest restRequest = RestRequest.getRequestForQuery(getString(R.string.api_version), serviceOrder);

			client.sendAsync(restRequest, new AsyncRequestCallback() {  
				@Override
				public void onSuccess(RestRequest request, RestResponse result) {
					try {
						
						Log.i("TPT", "Response is   :" + result);
						JSONObject jsonObject1 = new JSONObject(result         
								.toString());

						JSONArray jsonArray = jsonObject1
								.getJSONArray("records");

						serviceOrderList = new ArrayList<ServiceOrderModel>();
						activityDetailsList = new HashMap<String, ArrayList<ActivityModel>>();
						
						Gson _gson = new Gson();
						for (int i = 0; i < jsonArray.length(); i++) {

							
							serviceOrderSubList = new ArrayList<ActivityModel>();
							
							if (!jsonArray.isNull(i)) {
								/*ServiceOrderModel bean = _gson.fromJson(
										jsonArray.getString(i),
										ServiceOrderModel.class);

								serviceOrderList.add(bean);*/
								

								ServiceOrderModel bean = _gson.fromJson(jsonArray.getString(i),ServiceOrderModel.class);
								String ID = jsonArray.getJSONObject(i).getString("Id");
								
								JSONObject siteObject = jsonArray.getJSONObject(i);
								try{
								if (siteObject.getJSONObject("FConnect__Activities__r") != null) {
									Log.i("NCS","FConnectActivities   ");
									JSONArray siteArray = siteObject.getJSONObject("FConnect__Activities__r").getJSONArray("records");
									Log.i("NCS","siteArrayLength  "+siteArray.length());

									for (int j = 0; j < siteArray.length(); j++) {
										if (!siteArray.isNull(j)) {
											ActivityModel bean1 = _gson.fromJson(
													siteArray.getString(j),
													ActivityModel.class);
										serviceOrderSubList.add(bean1);
										}
										
									}
									activityDetailsList.put(ID,serviceOrderSubList);       
									serviceOrderList.add(bean);
								}
								}catch (Exception e) {
								}
							

							}

						}

						showRecords();

					} catch (Exception e) {
						
						Log.i("NCS","Exception is  :"+e.getMessage());
						onError(e);
					}
				}

				@Override
				public void onError(Exception exception) {
					EventsObservable.get().notifyEvent(EventType.RenditionComplete);
				}
			});



		} catch (Exception e) {
			Log.i("NCS","Exception  2 is  :"+e.getMessage());
		}

	}


	public void showRecords(){
		ServiceOrderAdapter adapter = new ServiceOrderAdapter(getActivity(),serviceOrderList);
		lv.setAdapter(adapter);
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
		// TODO Auto-generated method stub
		setHasOptionsMenu(false);
		listener.onWarehouseClicked(position);
	}

	
}
